package _61_序列化二叉树;

class TreeNode {
    int val = 0;
    TreeNode left = null;
    TreeNode right = null;

    public TreeNode(int val) {
        this.val = val;

    }

}
public class Solution {
    int index=0;
    void serializeDigui(TreeNode root,StringBuilder sb){
        if(root==null){
            sb.append("#!");
            return;
        }
        sb.append(root.val);
        sb.append("!");
        serializeDigui(root.left,sb);
        serializeDigui(root.right,sb);

    }
    String Serialize(TreeNode root) {
        StringBuilder sb = new StringBuilder();
        serializeDigui(root,sb);
        return sb.toString();
    }
    TreeNode Deserialize(String str) {
        if(str.length()==0) return null;
        String nodes[] = str.split("!");
        TreeNode root = DeserializeDigui(nodes);
        return root;
    }

    TreeNode DeserializeDigui(String[] nodes){
        if(nodes[index].equals("#")){
            index++;
            return null;
        }
        TreeNode root = new TreeNode(Integer.parseInt(nodes[index++]));
        root.left = DeserializeDigui(nodes);
        root.right = DeserializeDigui(nodes);
        return root;

    }

    public static void main(String[] args) {
        TreeNode treeNode = new TreeNode(8);
        treeNode.left = new TreeNode(6);
        treeNode.left.left = new TreeNode(10);
        treeNode.left.right = new TreeNode(5);

        treeNode.right = new TreeNode(7);
        treeNode.right.left= new TreeNode(9);
        treeNode.right.right = new TreeNode(11);
        Solution solution = new Solution();
        String s =solution.Serialize(treeNode);
        System.out.println(s);
        TreeNode t =solution.Deserialize(s);
        System.out.println(s);
    }
}
